﻿using FriendAnalyzer.Business;
using FriendAnalyzer.Infrastructure.Facebook;
using FriendAnalyzer.Infrastructure.Facebook.Interfaces;
using FriendAnalyzer.Infrastructure.Files;
using FriendAnalyzer.Infrastructure.MachineLearning.Analysis;
using FriendAnalyzer.UI.Common;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Security.Authentication.Web;
using Windows.UI.Xaml.Navigation;
using System.Linq;
using FriendAnalyzer.Infrastructure.MachineLearning.Model;

namespace FriendAnalyzer.UI.Views
{
    public sealed partial class LoginPage : LayoutAwarePage
    {
        private const string _fbId = "151352494889065";
        private const string _fbSecret = "2656c55dcfe4b26ce6c3076c3600f6e8";

        public LoginPage()
        {
            this.InitializeComponent();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var authenticator = new FacebookAuth(_fbId, _fbSecret);
            var api = await authenticator.TryGetAPIAsync();
            if (api == null)
            {
                api = await LoginUser(authenticator);
            }

            UseApi(api);
        }

        private async Task<IFriendsAPI> LoginUser(IFacebookAuth authenticator)
        {
            var loginUri = authenticator.GetLoginUri();
            var redirectUri = authenticator.RedirectUri;
            var options = WebAuthenticationOptions.None;

            var result = await WebAuthenticationBroker.AuthenticateAsync(options, loginUri, redirectUri);
            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var parsed = authenticator.GetAuthenticationResult(result.ResponseData);
                if (parsed.IsSuccesful())
                {
                    return parsed.GetAPI();
                }
                else
                {
                    Navigate.ToGenericError(result.ResponseData);
                }
            }
            else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                Navigate.ToNotAuthenticatedError();
            }
            else
            {
                Navigate.ToGenericError(result.ResponseData);
            }

            return null;
        }

        private async void UseApi(IFriendsAPI api)
        {
            var service = new AggregateService(api, new FileManager());

            //var data = await service.GetFriendsDataAsync();

            Navigate.ToMainPage(service);
        }
    }
}
